/**
 * 
 */
package com.projectsquirrel;

import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

/**
 * @author Arthi
 *
 */
public class DateTimeScreen extends Activity {

		//For Date
	    private TextView mDateDisplay;
	    private Button mPickDate;
	    private ImageButton settingsIconButton;
	    private ImageButton infoIconButton;
	    private int mYear;
	    private int mMonth;
	    private int mDay;
	    static final int DATE_DIALOG_ID = 0;
	    static Observation newObs;
	    
	    //location
	    private TextView tvLocationText;
	    private LocationManager locmgr = null;
	    static double lat;
	    static double lng;
	    
	    //For Time
	    private TextView mTimeDisplay;
	    private Button mPickTime;
	    private int mHour;
	    private int mMinute;
	    static final int TIME_DIALOG_ID = 1;


	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.datetime);

	        //Get data captured from newObservation.java
	        //newObs = newObservation.getResults();
	        
	        // capture our View elements
	        settingsIconButton = (ImageButton) findViewById(R.id.settingnfoScreenIcon);
		    infoIconButton = (ImageButton) findViewById(R.id.infoScreenIcon);
	        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
	        mPickDate = (Button) findViewById(R.id.pickDate);
	        mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
	        mPickTime = (Button) findViewById(R.id.pickTime);
	        
	        //Location
	        tvLocationText = (TextView) findViewById(R.id.locationText);
	        //grab the location manager service
	        locmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	        
	       // Location location = locmgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
	        
	        Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault() );
	        try{
	        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
	        String zipCode = addresses.get(0).getPostalCode();
	        tvLocationText.setText(zipCode);
	        }
	        catch(Exception e){
	        	tvLocationText.setText(e.toString());
	        }
	        //Location end
	        
	        
	        // add a click listener to the button
	        mPickDate.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	                showDialog(DATE_DIALOG_ID);
	            }
	        });
	        
	        settingsIconButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent i = new Intent(DateTimeScreen.this, settingsMenu.class);
			        startActivity(i);
				}	    	
		    });
	        
		    infoIconButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent i = new Intent(DateTimeScreen.this, infoMenu.class);
			        startActivity(i);
				}	    	
		    });

	        // get the current date
		    TimeZone tz = TimeZone.getTimeZone("America/Chicago");
	        final Calendar cDate = Calendar.getInstance(tz);
	        mYear = cDate.get(Calendar.YEAR);
	        mMonth = cDate.get(Calendar.MONTH);
	        mDay = cDate.get(Calendar.DAY_OF_MONTH);

	        // display the current date
	        updateDisplayDate();
	        
	        // add a click listener to the button
	        mPickTime.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	                showDialog(TIME_DIALOG_ID);
	            }
	        });

	        // get the current time
	        final Calendar cTime = Calendar.getInstance(tz);
	        mHour = cTime.get(Calendar.HOUR_OF_DAY);
	        mMinute = cTime.get(Calendar.MINUTE);

	        // display the current time
	        updateDisplayTime();
	    }
	    
	    
	    // updates the date in the TextView
	    private void updateDisplayDate() {
	        mDateDisplay.setText(
	            new StringBuilder()
	                    // Month is 0 based so add 1
	                    .append(mMonth + 1).append("-")
	                    .append(mDay).append("-")
	                    .append(mYear).append(" "));
	        
	        //newObs.year = mYear;
	        //newObs.month = mMonth +1;
	        //newObs.day = mDay;
	    }
	    
	    
	    private void updateDisplayTime() {
	        mTimeDisplay.setText(
	            new StringBuilder()
	                    .append(pad(mHour)).append(":")
	                    .append(pad(mMinute)));
	        
	        //newObs.hour = mHour;
	        //newObs.minute = mMinute;
	    }

	    private static String pad(int c) {
	        if (c >= 10)
	            return String.valueOf(c);
	        else
	            return "0" + String.valueOf(c);
	    }
	    
	    // the callback received when the user "sets" the date in the dialog
	    private DatePickerDialog.OnDateSetListener mDateSetListener =
	            new DatePickerDialog.OnDateSetListener() {

	                public void onDateSet(DatePicker view, int year, 
	                                      int monthOfYear, int dayOfMonth) {
	                    mYear = year;
	                    mMonth = monthOfYear;
	                    mDay = dayOfMonth;
	                    updateDisplayDate();
	                }
	            };
	            
	            // the callback received when the user "sets" the time in the dialog
	            private TimePickerDialog.OnTimeSetListener mTimeSetListener =
	                new TimePickerDialog.OnTimeSetListener() {
	                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
	                        mHour = hourOfDay;
	                        mMinute = minute;
	                        updateDisplayTime();
	                    }
	                };
	            
	            @Override
	            protected Dialog onCreateDialog(int id) {
	                switch (id) {
	                case DATE_DIALOG_ID:
	                    return new DatePickerDialog(this,
	                                mDateSetListener,
	                                mYear, mMonth, mDay);
	                case TIME_DIALOG_ID:
	                    return new TimePickerDialog(this,
	                            mTimeSetListener, mHour, mMinute, false);
	                }
	                return null;
	            }
	            
	            //Location
	          //Start a location listener
	            LocationListener onLocationChange=new LocationListener(){
	                public void onLocationChanged(Location loc) { 
	                    lat = (int) Math.round(loc.getLatitude()*1.0e6);
	                    lng = (int) Math.round(loc.getLongitude()*1.0e6);
	                }

					@Override
					public void onProviderDisabled(String arg0) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onProviderEnabled(String provider) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onStatusChanged(String provider, int status,
							Bundle extras) {
						// TODO Auto-generated method stub
						
					}
					
//					@Override
//					protected void onStop() {
//						/* may as well just finish since saving the state is not important for this toy app */
//						finish();
//						super.onStop();
//					}
	            };
	            
	            
	           
	        
}
